package com.it.config;

import org.apache.ibatis.logging.slf4j.Slf4jImpl;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/*
 * 持久层配置：连接池，sqlSessionFactory、Mapper代理对象
 * */
@Configuration
public class MapperConfig {
    // sqlSessionFactory加入到IOC容器
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        // 指定配置文件等信息
        // 指定数据库连接对象
        sessionFactoryBean.setDataSource(dataSource);
        // 指定mybatis配置文件功能，使用代码的形式
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        // 开启驼峰式映射
        configuration.setMapUnderscoreToCamelCase(true);
        // 开启日志输出
        // configuration.setLogImpl(Slf4jImpl.class);
        // 开启resultMap自动映射
        configuration.setAutoMappingBehavior(AutoMappingBehavior.FULL);
        sessionFactoryBean.setConfiguration(configuration);
        // 设置别名
        sessionFactoryBean.setTypeAliasesPackage("com.it.pojo");
        return sessionFactoryBean;
    }

    // Mapper代理对象加入到IOC容器
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.it.mapper");
        return mapperScannerConfigurer;
    }
}
